"""
Python的数据结构
序列：一块可以存放多个值的连续空间。
列表：[]           可变           有序          可重复
元组：()          不可变          有序          可重复
字典：{key：value} 可变           无序          可重复[value值是可以重复，key是不能重复，列表不能作为字典的key值]
集合：{}           可变           无序          不可重复
字符串：''或""      不可变         有序           可重复
索引：通过这种方式可以访问到单个元素的值。
序列名[索引值]
为正数时，起始索引是从0开始，从左向右进行依次递增，直到序列中最后一个元素的位置结束。
为负数时，起始索引是从-1开始，从右向左进行依次递减，直到序列中第一个元素的位置结束。
切片：通过这种方式可以访问到多个元素的值。
序列名[起始索引：结束索引：步长]
起始索引：开始的索引值，可以省略不写，默认值为序列中第一个元素的位置或序列中最后一个元素的位置，包含该位置。
结束索引：结束的索引值，可以省略不写，默认值为序列中最后一个元素的位置结束或第一个元素的位置结束，不包含该位置[采用默认值的话，他是包含全部的把内容]
步长：自增的量。可以省略不写，默认值为1.
为正数时，取值范围是从左向右进行取值；
为负数时，取值范围是从右向左进行取值；
如果省略的是步长，最后一个冒号可以省略不写，
如果省略的是起始索引和结束索引的话，他们中间的冒号就必须保留。



"""
# li = [1,2,3,4,5,6,7,8,9]
# # del li
# # print(li,type(li))
# print(li[2::-1])

# num_list = [11,22,33,44,55,66,77,88,99]
# print(num_list[2:5])
# print(num_list[-1:-5:-2])
# print(num_list[2:7:2])
# print(num_list[::-1])
# print(num_list[-2::-2])
# print(num_list[:6:])
# print(num_list[:6:-1])
# print(num_list[2::-1])

# print(num_list[4:1:1])
# print(num_list[100:200:1])

# li = [1,2,3,4,5,6,7,8,9]
# li.append(10)
# li.insert(3,10)
# li.extend([11,12,13])
# li.remove(30)
# li.pop(5)
# del li[5]
# li[5] = 66
# print(li)
# for i in range(len(li)):
#     print(li[i])

# for i in li:
#     print(i)

# num = (1,2,3,4,5,6,7,8,9)
# del num
# n = list(num)
# n1 = tuple(n)
# print(num,type(num))
# print(n,type(n))
# print(n1,type(n1))

# print(num+(10,11,12))

# print(type(int('123')))

info = {'name':'zhangsan', 'age':18, 'sex':'男', 'hobby':['吃饭','睡觉','打豆豆']}
# del info
# info['name'] = 'lisi'
# info['手机号'] = '123456789'
# info.update({'name':'wangwu','手机号':'987654321','age':20})
# del info['name']
# print(info.pop('name1', '键不存在'))
# info.clear()
# print(info,type(info))
# print(info['name'])
# print(info.get('name'))
# for i in info.items():
#     print(i)
# for i in info.keys():
#     print(i)
# for i in info.values():
#     print(i)

# num = {1,2,3,4,5,6,7,8,9}
# del num
# n = set()
# num.add(10)
# num.update([11,22,33])
# num.remove(90)
# num.discard(90)
# num.pop()
# num.clear()
# print(num,type(num))
# print(n,type(n))

# 创建两个集合
# set1 = {1,2,3,5,6}
# set2 = {2,4,6,8}
# # 交集
# print("交集:",set1&set2)
# # 并集
# print("并集:",set1|set2)
# # 差集 set1-set2
# print("差集set1-set2:",set1-set2)
# # 差集 set2-set1
# print("差集set2-set1:",set2-set1)
# # 对称差集
# print("对称差集:",set1^set2)

# srt1 = """
#
# hello world
#
# """
# print(srt1,type(srt1))

# srt1 = 'hello'
# srt2 = 'world'
# str3 = 'he-llo wo-rld'

# print('-'.join([srt1,srt2]))
# print(str3.split('-',2))

# str1 = "姓名:{},年龄:{},性别:{}"
# str2 = "姓名:{0},年龄:{1},性别:{2}"
# str3 = "姓名:{name},年龄:{age},性别:{sex}"
# str4 = "身高:{:.2f},体重:{:.1f},{:.2%}"
# # 系统默认参数
# print(str1.format("张飞",25,"男"))
# # 位置参数
# print(str2.format("孙二娘",30,"女"))
# # 关键字参数
# print(str3.format(name = "关羽",age = 30,sex = "男"))
# # 对小数的处理
# print(str4.format(1.789,65.69,0.213456))


import random
import string

# 列表练习
list1 = [1, 2, 3, 4, 5]
list1.append(6)
list1.remove(3)
list1[1]=8
list1.index(8)
# for i in list1:
#     print(i)
#print(list1)
list2 = [7, 8, 9]
for i in list2:
    list1.append(i)
list3 = [10, 11, 12]
list1.extend(list3)
#print(list1[2:5:1])
list1.pop(2)
list1.insert(2, 13)
list1.insert(3, 14)


my_list = [3, "apple", 9, "banana", 7, "cherry", 2, "date", 5, "elderberry"]
my_list.append("fig")
my_list.remove("banana")
my_list[6] = "grape"
print(my_list.index("cherry"))
for i in my_list:
    print(i)
my_list.insert(5, "kiwi")
print(my_list[2])
print(my_list[-2])
print(my_list[2:7])
print(my_list[::-1])
#对列表中的字符串进行排序，并保留数字在原位。
strings = sorted([item for item in my_list if isinstance(item, str)])

sorted_list = []
string_index = 0

for item in my_list:
    if isinstance(item, str):
        sorted_list.append(strings[string_index])
        string_index += 1
    else:
        sorted_list.append(item)
print(sorted_list)
#将my_list中的数字替换为它们对应的字符串形式（如1->'one'），不改变列表中原有的字符串。
num_to_str = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6:'six', 7:'seven', 8: 'eight', 9: 'nine'}

for i in range(len(my_list)):
    if isinstance(my_list[i], int):
        my_list[i] = num_to_str[my_list[i]]

nums = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58,
        60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
nums1 = nums.copy()

nums2 = []
for i in range(len(nums)):
    nums[i] *= nums[i]
    nums2.append(nums[i])
print(nums2)

numb3 = []
for item in nums2:
    if item > 1000:
        nums2.remove(item)
    else:
        numb3.append(item)
print(numb3)

nums.reverse()

print(nums[:10])
nums1.extend([101,102,103])
print(nums1)

sum = 0
for i in range(len(nums1)):
    sum += nums1[i]
print(sum/len(nums1))

max = 0
for i in range(len(nums1)):
    if nums1[i] > max:
        max = nums1[i]

min = 100
for i in range(len(nums1)):
    if nums1[i] < min:
        min = nums1[i]
print(min)

nums1.sort()
print(nums1)
print(nums1[0],nums1[-1])

print(nums1.index(11))

for i in range(len(nums1)):
    nums1[i] = str(nums1[i])
print(nums1)
for i in nums1:
    i = str(i)
print(nums1)

for i in range(len(nums1)):
    nums1[i] = float(nums1[i])
print(nums1)

count = 0
for i in range(len(nums1)):
    if nums1[i] > 50:
        count += 1
print(count)

nums1.insert(2,99)

nums1.pop()

double_nums = [x*2 for x in nums1]

list1 = []
list2 = []
for i in range(len(nums1)):
    if nums1[i] > 50:
        list1.append(nums1[i])
    elif nums1[i] < 50:
        list2.append(nums1[i])
print(list1)
print(list2)

dict1 = {}
for i in range(len(nums1)):
    dict1[nums1[i]] = i
print(dict1)


for index, value in enumerate(nums1):
    print(index, value)

random_element = random.choice(nums1)

with open('numbers.txt', 'w') as file:
    for item in nums1:
        file.write(str(item) + '\n')

# 字典练习
person_info = {
    "name": "Alex",
    "age": 30,
    "country": "USA",
    "language": ["English", "Spanish"],
    "is_student": False
}

print(person_info["name"])

person_info["age"] = 31

person_info["height"] = 175

person_info.pop("is_student")

print(person_info)

for key, value in person_info.items():
    print(key, value)

if person_info.get("email") in person_info:
    print("Email already exists")
else:
    person_info["email"] = "alex@example.com"
    print(person_info)

person_info["language"] = "English"
print(person_info)

print(len(person_info["language"]))

person_info["language"].append("French")
print(person_info["language"])

str1 = "hobby"
for i in range(3):
    str1 += str(i)
    person_info[str1] = i

print(person_info)

# 字典练习

employees = {
    101: {
        "name": "Alice",
        "age": 30,
        "gender": "Female",
        "position": "Data Scientist",
        "team": "Research",
        "salary_history": [70000, 80000, 90000]
    },
    # 更多员工数据...
}

employees[102] = {
    "name": "Bob",
    "age": 35,
    "gender": "Male",
    "position": "Software Engineer",
    "team": "Engineering",
    "salary_history": [60000, 70000, 80000]
}

employees.pop(102)
print(employees)

employees[101]["age"] = 31
print(employees[101]["age"])

employees[101]["salary_history"].append(95000)
print(employees[101]["salary_history"])

for key, value in employees.items():
    if value["age"] > 25:
        print(value["name"],value["age"])


for key, value in employees.items():
    value["bonus"] = value["salary_history"][-1] * 0.1

print(employees)

employees[101]["position"] = "Senior Data Scientist"
print(employees[101]["position"])

for key, value in employees.items():
    value.pop("gender")
print(employees)

dict1 = {}

for key, value in employees.items():
    dict1[value["name"]] = value["position"]

print(dict1)

# 字符串练习
s = "Hello, Python world!"
print(len(s))
print(s.count("o"))
print(s.upper())
print(s.lower())
print(s.find("Python"))
print(s.replace("world", "universe"))
if s.startswith("Hello"):
    print("是")
else:
    print("不是")

if s.endswith("!"):
    print("是")
else:
    print("不是")

print(s.split(","))
s = s.removesuffix("!")
print(s)

print(s[::-1])

print(s[7:13])

s = s.replace("Hello, ", '')
print(s)

s1 = "Hello,"
s2 = "world!"
s = s1 + s2
print(s)

s2 = 2021
s = f"Hello, {s2}"
print(s)

print(s.find("a"))
print(s.rfind("e"))

print(s.count(" "))

for i in range(len(s)):
    print(i, s[i])

s = list(s)
print(s)

s.sort()
s1 = "".join(s)
print(s1)

if s1.isdigit():
    print("是")
else:
    print("不是")

lst = ['Hello,', 'Python', 'World!']
s = " ".join(lst)
print(s)

a = 100
st = "Number: %d" % a
print(st)

print(s.isupper())
print(s.islower())

st1 = [1,2,3]
s12 = "-".join(str(i) for i in st1)
print(s12)

lst1 = []
for i in range(len(s)):
    if s[i] == "o":
        lst1.append(i)
print(lst1)

print(s.replace("o", "O", 1))
substring = "amazing "

position = 7
new_s = s[:position] + substring + s[position:]

print(new_s)

s = "Python is great!"
reversed_s = ""
for i in range(len(s) - 1, -1, -1):
    reversed_s += s[i]
print(reversed_s)

count = 0
for i in range(len(s)):
    if s[i] == "t":
        count += 1
print(count)

s = s.replace(" ","_")
print(s)


s2 = "A man, a plan, a canal, Panama!"

s2 = s2.lower()

# 2. 去除标点和空格
s2_cleaned = ''.join(char for char in s2 if char not in string.punctuation and char != ' ')

# 3. 检查是否为回文
is_palindrome = s2_cleaned == s2_cleaned[::-1]

if is_palindrome:
    print("字符串是回文。")
else:
    print("字符串不是回文。")

print(s.find("is"))

s = s.replace("great","awesome",1)
print(s)
# 1. 计算中间位置
mid = len(s) // 2
# 2. 切分字符串
first_half = s[:mid]  # 前半部分
second_half = s[mid:]  # 后半部分
# 3. 以相反的顺序拼接
result = second_half + first_half
print(result)

capitalized_words = [word.capitalize() for word in s.split()]

print(capitalized_words)


def encrypt(s):
    encryption_dict = {
        'a': 'm', 'b': 'n', 'c': 'o', 'd': 'p',
        'e': 'q', 'f': 'r', 'g': 's', 'h': 't',
        'i': 'u', 'j': 'v', 'k': 'w', 'l': 'x',
        'm': 'y', 'n': 'z', 'o': 'a', 'p': 'b',
        'q': 'c', 'r': 'd', 's': 'e', 't': 'f',
        'u': 'g', 'v': 'h', 'w': 'i', 'x': 'j',
        'y': 'k', 'z': 'l'
    }
    encrypted_string = ''.join(encryption_dict.get(char, char) for char in s)
    return encrypted_string

s3 = "encryption"
encrypted_s3 = encrypt(s3)
print(encrypted_s3)


import datetime
import random

money = 3000
goods = {'洗衣机': 500, '空调': 300, '电视': 200, '冰箱': 400, '手机': 100}
goods_cart = []
discount = {1: {'洗衣机': 0.8}, 2: {'空调': 0.7}, 3: {'电视': 0.6}, 4: {'冰箱': 0.5}, 5: {'手机': 0.8},
            6: {'洗衣机': 0.7}, 7: {'空调': 0.8}, 8: {'电视': 0.7}, 9: {'冰箱': 0.9}, 10: {'手机': 0.6}}
random_discount = random.randint(0, 9)
print(random_discount)
while True:
    good = input("请输入商品：")
    if good not in goods:
        print("商品不存在，请重新输入")
        continue
    if money >= goods[good]:
        goods_cart.append(good)
        if good in discount[random_discount]:
            price = goods[good] * discount[random_discount][good]
            money -= price
        else:
            money -= goods[good]
        print("购物车中有：", goods_cart)
        print("剩余钱数：", money)
        x = input("是否需要继续添加购物车？按n键结束购物，任意键继续购物")
        if x == 'n':
            while True:
                y = input("是否需要退货？按y键退货，任意键结束购物")
                if y == 'y':
                    return_good = input("请输入退货商品：")
                    if len(goods_cart) > 0:
                        if return_good not in goods_cart:
                            print("商品不存在，请重新输入")
                            continue
                        else:
                            if return_good in discount[random_discount]:
                                price = goods[good] * discount[random_discount][return_good]
                                money += price
                                print("退货成功，已将", return_good, "退回仓库")
                                return_good = goods_cart.remove(return_good)
                                print("购物车中有：", goods_cart)
                                print("剩余钱数：", money)
                            else:
                                money += goods[return_good]
                                print("退货成功，已将", return_good, "退回仓库")
                                return_good = goods_cart.remove(return_good)
                                print("购物车中有：", goods_cart)
                                print("剩余钱数：", money)
                    else:
                        print("购物车为空，无法退货")
                        break
                else:
                    break
    else:
        print("余额不足，无法购买商品")
        break

print("购物结束，下单时间：", datetime.datetime.now())
print("卡内余额：", money)
print("购物清单：", goods_cart)
print("商品总价：", 3000 - money)
print("感谢您的购物，欢迎下次光临！")

